package com.FilePortal.controller;

import com.FilePortal.entity.File;
import com.FilePortal.service.FileServiceImpl;
import com.FilePortal.util.randomCode;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.List;

@Controller
//@RequestMapping("/file")
public class FileController {

	@Autowired
	@Qualifier("FileServiceImpl")
	private FileServiceImpl fileService;

	@RequestMapping("/test")
	public String list(Model model) {
		List<File> list = fileService.findAllFiles();
		model.addAttribute("list", list);
		return "test";
	}

	//上传文件以及授予取件码
	@RequestMapping(value = "upload", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public String upload(HttpServletRequest request, MultipartFile file) {
		//TODO:判断是否需要登录，判断文件大小
		//TODO:判断时间是否过期
		//TODO:二维码/直达链接下载
		//TODO:使用QQ用户注册
		System.out.println(request.getParameter("password"));
		System.out.println(request.getParameter("advance"));
		System.out.println(request.getParameter("times"));
		System.out.println(request.getParameter("days"));
		int days = 1;
		int times = 1;
		String password = request.getParameter("password");
		if (request.getParameter("advance").equals("true")) {
			days = Integer.parseInt(request.getParameter("days"));
			times = Integer.parseInt(request.getParameter("times"));
		}
		JSONObject json = new JSONObject();
		String path = request.getSession().getServletContext().getRealPath("/") + "\\file";
		Timestamp time1 = new Timestamp(System.currentTimeMillis());
		Timestamp time2 = new Timestamp(System.currentTimeMillis() + 86400000 * days);
		String code = randomCode.getRandomString();
		while (fileService.isExist(code)) {
			code = randomCode.getRandomString();
		}
		String fileName = code;
		json.put("code", code);
		java.io.File dir = new java.io.File(path, fileName);
		System.out.println(json);
		System.out.println(file.getOriginalFilename());


		//写入数据库操作
		try {
			file.transferTo(dir);
			System.out.println("the MD5 is " + com.FilePortal.util.fileMD5.md5(dir));
			File fileInfo = new File();
			fileInfo.setFile(path);
			fileInfo.setCode(code);
			fileInfo.setUploadTime(time1);
			fileInfo.setDeltime(time2);
			fileInfo.setName(file.getOriginalFilename());
			fileInfo.setRemain(days);
			fileInfo.setPassword(com.FilePortal.util.getMD5.getMD5(password));
			fileService.addFile(fileInfo);
			json.put("status", 0);
		} catch (IOException e) {
			e.printStackTrace();
			json.put("status", -1);
			return json.toString();
		}
		return json.toString();

	}

	public String saveFile(File fileinfo, MultipartFile file) {
		//TODO:前端不同的业务操作和文件的保存处理需要分离（暂时不需要）


		return "";
	}

	@RequestMapping(value = "download", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	@ResponseBody
	public String download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		password = com.FilePortal.util.getMD5.getMD5(password);
		if (fileService.isExist(code)) {
			if (fileService.getPassword(code) != null) {
				if (!fileService.getPassword(code).equals(password)) {
					return "{\"Error\":\"-2\"}";//密码错误
				}
			}
			File file = fileService.findOneFile(code);
			fileService.getOnceFile(code);
			String name = file.getName();
			response.setCharacterEncoding("UTF-8");
			//设置ContentType字段值
			response.setContentType("text/html;charset=utf-8");
			response.addHeader("Content-type", "appllication/octet-stream");
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "ISO8859-1"));
			//通知文件流读取文件
			InputStream in = request.getServletContext().getResourceAsStream("file/" + code);
			//获取response对象的输出流
			OutputStream out = response.getOutputStream();
			byte[] buffer = new byte[1024];
			int len;
			//循环取出流中的数据
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}


		}
		return "{\"Error\":\"-1\"}";//文件不存在、取件码错误
	}
}
